import { getHouseResDetail } from '../../api/houseRes'
import { addHouseMedia } from '../../api/houseMedia'
import { addVerRecord } from '../../api/verRecord'
import config from '../../config/index'
import { getToken, getUserInfo } from '../../utils/storage'
//@ts-ignore
import Dialog from '@vant/weapp/dialog/dialog'
interface MediaType {
  id: number
  url: string
  type: string
  poster?: string
  isPoster: boolean
}

Page({
  data: {
    config,
    houseRes: null as any,
    userInfo: {} as User,
    longitude: '',
    latitude: '',
    hidePhone: '',
    showVer: false,
    ver_user_name: '',
    ver_phone: '',
    ver_mark: '',
    verLoading: false,
    showUpload: false,
    tempList: [] as MediaType[],
    showShare: false,
    options: [
      { name: '微信', icon: 'wechat', openType: 'share' },
      { name: '朋友圈', icon: 'wechat-moments' }
    ],
  },
  getData() {
    const user = getUserInfo()
    if (user) {
      this.setData({
        userInfo: JSON.parse(user),
        ver_phone: JSON.parse(user).phone
      })
    }
  },
  async initDetail(id: string) {
    const res = await getHouseResDetail(id)
    if (res.statusCode === config.SUCCESS_CODE) {
      let detail = res.data
      detail.HouseMedia = detail.HouseMedia.map((item: any, index: number) => {
        return {
          id: index,
          url: config.BaseUrl + '/' + item.media_url,
          type: item.media_type,
          isPoster: item.isPoster
        }
      }) as MediaType[]
      detail.createdAt = new Date(detail.createdAt).toLocaleDateString('zh-CN')
      let hidePhone = detail.landload_phone.replace(/(\d{3})\d{4}(\d{4})/, '$1****$2')

      this.setData({
        houseRes: detail,
        longitude: detail.house_position.split(',')[0],
        latitude: detail.house_position.split(',')[1],
        hidePhone
      })
    } else {
      wx.showToast({
        title: '获取失败请重试',
        icon: 'none'
      })
    }
  },
  prviewMedia(e: WechatMiniprogram.TouchEvent) {
    let id = e.currentTarget.dataset.id
    wx.previewMedia({
      current: id,
      sources: this.data.houseRes.HouseMedia as WechatMiniprogram.MediaSource[]
    })
  },
  prviewTempMedia(e: WechatMiniprogram.TouchEvent) {
    let id = e.currentTarget.dataset.id
    wx.previewMedia({
      current: id,
      sources: this.data.tempList as WechatMiniprogram.MediaSource[]
    })
  },
  posterMedia(e: any) {
    if (this.data.houseRes.HouseMedia.some((item: HouseMedia) => item.isPoster === true)) {
      wx.showToast({
        title: '已有首图',
        icon: 'none'
      })
      return
    }
    let index = e.currentTarget.dataset.index
    let tempList = this.data.tempList.map((item: MediaType) => {
      return {
        ...item,
        isPoster: false
      }
    }) as MediaType[]
    tempList[index].isPoster = true
    this.setData({
      tempList
    })
  },
  delMedia(e: any) {
    let id = e.currentTarget.dataset.id
    let new_list = this.data.tempList.filter(item => item.id !== id)
    this.setData({
      tempList: new_list
    })
  },
  openPos() {
    wx.openLocation({
      longitude: Number(this.data.longitude),
      latitude: Number(this.data.latitude),
      address: this.data.houseRes.house_address
    })
  },
  callPhone() {
    Dialog.confirm({
      title: '联系房东',
      message: '是否联系房东，拨打房东号码'
    }).then(() => {
      wx.makePhoneCall({
        phoneNumber: this.data.houseRes.landload_phone
      })
    }).catch(() => { })
  },
  sharePage() {
    this.onShareChange()
  },
  onShareChange() {
    this.setData({ showShare: !this.data.showShare });
  },
  onShareSelect(event: any) {
    console.log(event);
    if (event.detail.name === '朋友圈') {
      wx.showToast({
        title: '点击右上角•••按钮进行分享',
        icon: 'none'
      })
    }
    this.onShareChange()
  },
  toHome() {
    wx.switchTab({
      url: '/pages/index/index'
    })
  },
  verFun() {
    if (!this.data.houseRes.house_status) return
    Dialog.confirm({
      title: '确认核销',
      message: '是否确认发起核销，将由客服审核核销'
    }).then(() => {
      this.changeVer()
    }).catch(() => { })
  },
  changeVer() {
    this.setData({
      showVer: !this.data.showVer
    })
  },
  changeUpload() {
    this.setData({
      showUpload: !this.data.showUpload
    })
  },
  async subVer() {
    this.setData({
      verLoading: true
    })
    let data: VerRecord = {
      ver_user_name: this.data.ver_user_name,
      ver_phone: this.data.ver_phone,
      ver_mark: this.data.ver_mark,
      houseResId: this.data.houseRes.id
    }
    const res = await addVerRecord(data)
    if (res.statusCode === config.CREATED_CODE) {
      wx.showToast({
        title: '提交成功',
        icon: 'success'
      })
      this.setData({
        verLoading: false
      })
      this.changeVer()
    } else {
      wx.showToast({
        title: '提交失败请重试',
        icon: 'none'
      })
      this.setData({
        verLoading: false
      })
    }
  },
  uploadVideo() {
    if (this.data.houseRes.HouseMedia.length === 9) {
      wx.showToast({
        title: '图片/视频数量已满',
        icon: 'none'
      })
      return
    }
    this.changeUpload()
  },
  setVideo() {
    let that = this
    wx.chooseMedia({
      count: 8,
      mediaType: ['mix'],
      sourceType: ['album', 'camera'],
      maxDuration: 60,
      success: function (res: any) {
        if (res.errMsg === 'chooseMedia:ok') {
          let media_list = res.tempFiles.map((item: any, index: number) => {
            return {
              id: index,
              url: item.tempFilePath,
              type: item.fileType,
              poster: item.thumbTempFilePath,
              isPoster: false
            }
          }) as MediaType[]
          if (media_list.some(item => item.type === 'video') && that.data.houseRes.HouseMedia.some((mItem: MediaType) => mItem.type === 'video')) {
            wx.showToast({
              title: '此房源已有视频，请重新上传',
              icon: 'none'
            })
            return
          }
          if (media_list.filter(item => item.type === 'image').length + that.data.houseRes.HouseMedia.filter((mItem: MediaType) => mItem.type === 'image').length > 8) {
            wx.showToast({
              title: '上传图片超过总数量，请重新上传',
              icon: 'none'
            })
            return
          }
          if (media_list.filter(item => item.type === 'video').length > 1) {
            wx.showToast({
              title: '视频数量只能上传1个，请重新上传',
              icon: 'none'
            })
            return
          }
          that.setData({
            tempList: media_list
          })
        }
      }
    })
  },
  addVideo() {
    if (this.data.tempList.length === 0) return
    wx.showLoading({
      title: '上传文件中'
    })
    let that = this
    this.data.tempList.forEach((item: MediaType) => {
      wx.uploadFile({
        url: config.BaseUrl + '/api/upload/image',
        filePath: item.url,
        name: 'file',
        success: async (res) => {
          const mediaRes = JSON.parse(res.data)
          if (mediaRes.statusCode !== config.CREATED_CODE) {
            wx.hideLoading()
            wx.showToast({ title: '上传文件失败', icon: 'none' })
            return
          }
          const file = mediaRes.data
          let data: HouseMedia = {
            media_url: file.path.replace(/\\/g, '/'),
            media_type: file.mimetype === 'image/jpeg' || file.mimetype === 'image/png' ? 'image' : 'video',
            houseResId: that.data.houseRes.id,
            sub_user: that.data.userInfo.id,
            isPoster: item.isPoster
          }
          const addMediaRes = await addHouseMedia(data)
          if (addMediaRes.statusCode !== config.CREATED_CODE) {
            wx.hideLoading()
            wx.showToast({ title: '上传失败，请重试', icon: 'none' })
            return
          }
        }
      })
    })
    wx.hideLoading()
    wx.showToast({
      title: '上传完成',
      icon: 'success'
    })
    this.setData({ showUpload: false })
    this.initDetail(this.data.houseRes.id)
  },
  onLoad(e: Record<string, string>) {
    if (!getToken()) {
      wx.showToast({
        title: '请先登录',
        icon: 'none'
      })
      setTimeout(() => {
        wx.switchTab({
          url: '/pages/me/me'
        })
      }, 1000)
      return
    }
    let id = e.id
    this.initDetail(id)
    this.getData()
  },
  onShareAppMessage() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: this.data.houseRes.house_name
        })
      }, 1000)
    })
    return {
      title: this.data.houseRes.house_name,
      path: `/pages/houseDetail/houseDetail?id=${this.data.houseRes.id}`,
      promise
    }
  },
  onShareTimeline() {
    const promise = new Promise(resolve => {
      setTimeout(() => {
        resolve({
          title: this.data.houseRes.house_name
        })
      }, 1000)
    })
    return {
      title: this.data.houseRes.house_name,
      path: `/pages/houseDetail/houseDetail?id=${this.data.houseRes.id}`,
      promise
    }
  }
})